package com.sicheng.metadata.juc.集合安全问题;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

public class ArrayListSecurity {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

        Resource resource = new Resource();
        new Thread(resource::consume, "a").start();
        new Thread(resource::produce, "b").start();

    }

    static class Resource {
        BlockingQueue<Integer> blockingDeque = new ArrayBlockingQueue<>(1);
         int x = 1;

        public void produce() {
            try {
                while (true) {
                    blockingDeque.put(x);
                    System.out.println(x);
                    TimeUnit.MILLISECONDS.sleep(300);
                }
            } catch (InterruptedException ignored) {
            }
        }

        public void consume() {
            try {
                while (true) {
                    int x = blockingDeque.take();
                    System.out.println(x - 1);
                }
            } catch (InterruptedException ignored) {
            }
        }
    }
}
